from flask import jsonify, request, render_template
from server import sqlscaleserver, sqluserserver
from . import user_api


@user_api.route('/users', methods=['GET'])
def get_all_users_route():
    search_query = request.args.get('search', '')
    user_list = sqluserserver.get_all_users(search_query)
    if search_query:
        return jsonify({'users': user_list})
    else:
        return render_template('users.html', userList=user_list)
        # return jsonify({'users': user_list})

@user_api.route('/users', methods=['POST'])
def add_user_route():
    if request.content_type != 'application/json':
        return jsonify({'error': 'Content-Type must be application/json'}), 400

    data = request.get_json()

    required_fields = ['name', 'identity_card', 'admission_no', 'gender', 'age', 'fertility_history', 'education_level',
                       'occupation', 'diagnosis', 'comorbidity', 'therapeutic_modality', 'methods_of_medical_cost_coverage','marital_status', 'phone',
                       'emergency_contact', 'emergency_contact_phone', 'address', 'agricultural_indicator', 'temperature_2_months', 'pulse_2_months', 'respiration_rate_2_months', 'blood_pressure_2_months']
    for field in required_fields:
        if field not in data or data[field] is None:
            return jsonify({'error': f'{field} 字段不能为空'}), 400

    try:
        data['agricultural_indicator'] = bool(data['agricultural_indicator'])
    except ValueError:
        return jsonify({'error': 'Invalid value for agricultural_indicator'}), 400
    # 添加用户并获取新创建用户的 ID
    user_id = sqluserserver.add_user(data)
    print(f'users中的user_id:{user_id}')
    # 创建心理量表新纪录
    sqlscaleserver.create_psychological_test_record(user_id)
    return jsonify({'message': '用户已创建'})

@user_api.route('/users/<int:user_id>', methods=['GET'])
def get_user_detail_route(user_id):
    user, psychological_records = sqluserserver.get_user_detail(user_id)
    if user:
        print(f'user:{user}')
        print(f'psychological_records:{psychological_records}')
        # return render_template('user_detail.html', user=user, psychological_records=psychological_records)
        return jsonify(user=user, psychological_records=psychological_records)
    else:
        return jsonify({'error': 'User not found'}), 404

@user_api.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user_route(user_id):
    sqluserserver.delete_user(user_id)
    return jsonify({'success': True, 'message': '用户已删除'})

@user_api.route('/users/<int:user_id>', methods=['PUT'])
def update_user_route(user_id):
    if request.content_type != 'application/json':
        return jsonify({'error': 'Content-Type must be application/json'}), 400

    data = request.get_json()
    if sqluserserver.update_user(user_id, data):
        return jsonify({'success': True, 'message': '用户已更新'})
    else:
        return jsonify({'error': 'User not found'}), 404

@user_api.route('/list', methods=['GET'])
def get_all_users_list():
    try:
        user_list = sqluserserver.get_all_users()
        # 提取所有用户的姓名和身份证号
        user_data = [{'name': user['name'], 'identity_card': user['identity_card'],'userid': user['id']} for user in user_list]

        # 如果用户列表为空，设置相应的错误信息
        if not user_data:
            return jsonify({
                'code': 40400,
                'err': 1,
                'message': '没有找到用户',
                'data': []
            })

        return jsonify({
            'code': 20000,
            'err': 0,
            'message': '查询成功',
            'data': user_data
        })
    except Exception as e:
        return jsonify({
            'code': 50000,
            'err': 2,
            'message': f'查询失败: {str(e)}',
            'data': []
        })

@user_api.route('/list', methods=['POST'])
def get_user_info():
    data = request.json
    identity_card = data.get('identity_card')
    user_list = sqluserserver.get_all_users()

    if not identity_card:
        return jsonify({"code": 40000, "err": 1, "message": "身份证号不能为空"}), 400

    for patient in user_list:
        if patient['identity_card'] == identity_card:
            return jsonify({"code": 20000, "err": 0, "message": "查询成功", "data": patient})

    return jsonify({"code": 40400, "err": 1, "message": "未找到该身份证号对应的患者信息"}), 404
@user_api.route('/problemlist', methods=['POST'])
def get_problem_list():
    data = request.json
    userid = data.get('userid')
    user_list = sqluserserver.get_problem_list()
    print(user_list)
    if not userid:
        return jsonify({"code": 40000, "err": 1, "message": "用户id不能为空"}), 400
    problem_list1=[]
    for problem_list in user_list:

        if problem_list['user_id'] == userid:
            problem_list1.append(problem_list)
    return jsonify({"code": 20000, "err": 0, "message": "查询成功", "problem_list": problem_list1})

    # return jsonify({"code": 40400, "err": 1, "message": "未找到该用户id对应的信息"}), 404

@user_api.route('/train', methods=['POST'])
def user_train():
    data = request.json
    identity_card = data.get('identity_card')

    if not identity_card:
        return jsonify({"code": 40000, "err": 1, "message": "缺少identity_card参数"}), 400

    ratings = sqluserserver.get_user_ratings(identity_card)

    return jsonify({"code": 20000, "err": 0, "message": "查询成功", "data": ratings})

@user_api.route('/train/rate', methods=['POST'])
def rate_train():
    data = request.json
    user_id=data.get('user_id')
    identity_card = data.get('identity_card')
    video_name = data.get('video_name')
    rating = data.get('rating')
    evaluate_text= data.get('suggestion')
    train_time_sum=data.get('train_time_sum')
    username=data.get('username')
    admission_no =data.get('admission_no')
    phone=data.get('phone')
    print(data)
    # result = {"status":"success","message":"success"}
    if not identity_card or not video_name or not rating:
        return jsonify({"code": 40000, "err": 1, "message": "缺少必要的参数"}), 400

    result = sqluserserver.insert_rating_sql(user_id, video_name, rating, train_time_sum,username,admission_no,phone)
    if evaluate_text:
        sqluserserver.insert_problem_sql(user_id, evaluate_text, video_name,username,admission_no)
    if result["status"] == "success":
        return jsonify({"code": 20000, "err": 0, "message": result["message"]})
    else:
        return jsonify({"code": 50000, "err": 1, "message": result["message"]}), 500







